package day10.handler.simpleChannelHandler;

import day10.packet.LoginRequestPacket;
import day10.packet.LoginResponsePacket;
import day10.util.LoginUtil;
import day10.util.session.Session;
import day10.util.session.SessionUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.Random;

/**
 * @author chenshijie
 * @date 2023/12/26 13:13
 */

public class LoginRequestHandler extends SimpleChannelInboundHandler<LoginRequestPacket> {

    private final static String USERNAME = "yu";
    private final static String PASSWORD = "password";

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, LoginRequestPacket loginRequestPacket) throws Exception {
        ctx.channel().writeAndFlush(login(ctx, loginRequestPacket));
    }

    private static boolean valid(LoginRequestPacket loginRequestPacket) {
        return true;
//        return USERNAME.equals(loginRequestPacket.getUsername()) && PASSWORD.equals(loginRequestPacket.getPassword());
    }

    private static LoginResponsePacket login(ChannelHandlerContext ctx, LoginRequestPacket loginRequestPacket) {
        LoginResponsePacket loginResponsePacket = new LoginResponsePacket();
        loginResponsePacket.setVersion(loginRequestPacket.getVersion());

        // 登录校验
        if (valid(loginRequestPacket)) {
            // 成功
            int userId = randomNumber();
            loginRequestPacket.setUserId(userId);
            loginResponsePacket.setStatus(200);
            loginResponsePacket.setMsg("登录成功");
            loginResponsePacket.setUsername(loginRequestPacket.getUsername());
            System.out.println(ctx.channel());
            System.out.println("用户id为" + userId + ",用户名为" + loginRequestPacket.getUsername() + "登录成功");
            LoginUtil.markAsLogin(ctx.channel());
            SessionUtil.bindSession(new Session(userId, loginRequestPacket.getUsername()), ctx.channel());
        } else {
            // 错误
            System.out.println("客户端校验失败");
            loginResponsePacket.setStatus(405);
            loginResponsePacket.setMsg("密码错误或者账号不存在");
        }
        return loginResponsePacket;
    }

    private static int randomNumber() {
        return new Random().nextInt(900000000) + 100000000;
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        SessionUtil.unBindSession(ctx.channel());
    }
}
